package com.yootoo.bsuser.rest;

import java.awt.image.BufferedImage;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.apache.tomcat.util.http.fileupload.ByteArrayOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.MessageChannel;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.yootoo.bsuser.entity.User;
import com.yootoo.bsuser.service.IUserService;
import com.yootoo.common.enums.ErrorEnum;
import com.yootoo.common.enums.RedisKeyContont;
import com.yootoo.common.enums.SysEnum;
import com.yootoo.common.exception.BizException;
import com.yootoo.common.requestVo.ReqUserGetVo;
import com.yootoo.common.requestVo.ReqUserLoginVo;
import com.yootoo.common.requestVo.ReqUserRegisterVo;
import com.yootoo.common.responseVo.ResultBean;
import com.yootoo.common.utils.ValidUtil;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;


/**
 * Created by Administrator on 2017/8/16.
 */
@RestController
public class UserProvider {

	private static final Logger log = LoggerFactory.getLogger(UserProvider.class);

	@Autowired
	private IUserService userService;

	@Autowired
	DefaultKaptcha defaultKaptcha;
	
	/*@Autowired
	private AmqpTemplate rabbitTemplate;*/
	
//	@Autowired // 通过直接注入的方式注入通道，input Sink.INPUT
//    private MessageChannel input;

    // 当有多个通道时，可通过名称指定
   // @Autowired
    //@Qualifier("input2") // 通过直接注入的方式注入通道，input Sink.INPUT
    //private MessageChannel inputtest;

	@ResponseBody
	@RequestMapping(value = "/sendMsg", method = RequestMethod.GET, produces = { "application/json;charset=UTF-8" })
	@ApiOperation(value = "用户登录首页", notes = "用户登录首页")
	@ApiImplicitParam(name = "name", value = "用户Name", required = true, dataType = "String", paramType = "path")
	public String index(String name) {
//		input.send(MessageBuilder.withPayload("**************From SinkSender").build());// 发到input通道，有消费者
		//inputtest.send(MessageBuilder.withPayload("#################From SinkSender").build());// 发到input2通道，无消费者
		
	/*	String sendMsg = "hello message" + new Date();
		System.out.println("Sender1 : " + sendMsg);
		this.rabbitTemplate.convertAndSend("exchange", "topic.message", sendMsg);*/
		// ServiceInstance instance = client.getLocalServiceInstance();
		// log.info(""+instance.getHost()+"|"+instance.getServiceId());
		/*String sendMsg2 = "hello messages" + new Date();
		System.out.println("Sender2 : " + sendMsg);
		this.rabbitTemplate.convertAndSend("exchange", "topic.messages", sendMsg2);*/
		return "hello world";
	}


	@ResponseBody
	@ApiOperation(value="判断用户是否存在", notes="根据user的name来判断用户是否存在")
	//@ApiImplicitParam(name = "name", value = "用户Name")
	@RequestMapping(value = "/existUser",method =RequestMethod.GET, produces = { "application/json;charset=UTF-8"})
	public ResultBean existUser(@RequestParam("name") String name) {
		// 参数校验
		if (StringUtils.isEmpty(name)) {
			return new ResultBean(new BizException(ErrorEnum.PARAM_CHECK_NOTEMPTY, "用户名"));
		}
		User user = new User();
		user.setName(name);
		// 返回结果
		ResultBean<Boolean> resultBean = new ResultBean<Boolean>();
		boolean isExist = false;
	
		log.info("==================用户：" + user.getName() + "校验是否存在");
		User resUser = userService.selectByName(user);
		if (resUser != null) {
			isExist = true;
			log.info("==================用户：" + user.getName() + "校验存在");
		}
		log.info("==================用户：" + user.getName() + "校验不存在");
		resultBean.setData(isExist);
		return resultBean;
	}

	@ResponseBody
	@ApiOperation(value="创建用户", notes="根据User对象创建用户")
	@ApiImplicitParam(name = "reqUser", value = "用户注册请求user", required = true, dataType = "ReqUserRegisterVo")
	//@ApiImplicitParam(name = "name", value = "用户ID", required = true, dataType = "Integer", paramType = "path")
	@RequestMapping(value = "/user", method=RequestMethod.POST,produces = { "application/json;charset=UTF-8" })
	public ResultBean<User> register(@RequestBody @Valid ReqUserRegisterVo reqUser, BindingResult result) {
		// 参数校验
		@SuppressWarnings("unchecked")
		ResultBean<User> validresult = ValidUtil.validByBindingResult(result);
		if (validresult != null) {
			return validresult;
		}
		// 返回结果
		ResultBean<User> resultBean = new ResultBean<User>();
		User user = new User();
		user.setName(reqUser.getName());
		User resUser = userService.selectByName(user);
		if (resUser != null) {
			return new ResultBean<User>(new BizException(ErrorEnum.ADDERROR_EXISTNAME, SysEnum.USER));
		}

		log.info("==================用户：" + user.getName() + "开始注册");
		boolean addFlag = false;
		try {
			BeanUtils.copyProperties(reqUser, user);
			addFlag = userService.addUser(user);
		} catch (Exception e) {
			return new ResultBean<User>(new BizException(ErrorEnum.OPRATE_EEROR));
		}

		if (!addFlag) {
			return new ResultBean<User>(new BizException(ErrorEnum.REGISTER_NOTPASS, "用户"));
		}
/*		for(int i = 0 ;i<10 ;i++) {
			this.rabbitTemplate.convertAndSend("registerUserQueue", "success");
			
			this.rabbitTemplate.convertAndSend("objectQueue", user);	
		}*/
		log.info("==================用户：" + user.getName() + "注册成功");
		return resultBean;
	}

	@RequestMapping("/verifiCode")
	@ApiIgnore
	public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
			throws Exception {
		byte[] captchaChallengeAsJpeg = null;
		ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
		try {
			// 生产验证码字符串并保存到session中
			String createText = defaultKaptcha.createText();
			httpServletRequest.getSession().setAttribute("vrifyCode", createText);
			// 使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
			BufferedImage challenge = defaultKaptcha.createImage(createText);
			ImageIO.write(challenge, "jpg", jpegOutputStream);
		} catch (IllegalArgumentException e) {
			httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;
		}

		// 定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
		captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
		httpServletResponse.setHeader("Cache-Control", "no-store");
		httpServletResponse.setHeader("Pragma", "no-cache");
		httpServletResponse.setDateHeader("Expires", 0);
		httpServletResponse.setContentType("image/jpeg");
		ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
		responseOutputStream.write(captchaChallengeAsJpeg);
		responseOutputStream.flush();
		responseOutputStream.close();
		
	}

	@ResponseBody
	@ApiIgnore
	@RequestMapping(value = "/login", method = RequestMethod.POST)
//	@Cacheable(value="userCache", key= "'"+RedisKeyContonts.LOGIN_USER+"'+#name")
	public ResultBean<User> login(@Valid @RequestBody ReqUserLoginVo requser,
			HttpServletRequest httpServletRequest) {
		// 返回参数
		ResultBean<User> resultBean = new ResultBean<>();

		// 校验码
	/*	String captchaId = (String) httpServletRequest.getSession().getAttribute("vrifyCode");
		String parameter = httpServletRequest.getParameter("vrifyCode");
		System.out.println("Session  vrifyCode " + captchaId + " form vrifyCode " + parameter);

		if (!String.valueOf(captchaId).equals(requser.getVerifiCode())) {
			return new ResultBean<User>(new ParamException(ErrorEnum.VERIFICODE_NOTPASS));
		}*/
		User user = new User();
		BeanUtils.copyProperties(requser, user);
		log.info("==================用户：" + user.getName() + "开始登陆");
		User findUser = userService.selectByNamePassWord(user);
		if (findUser == null) {
			log.info("==================用户：" + user.getName() + "用户名或密码错误");
			return new ResultBean<User>(new BizException(ErrorEnum.LOGIN_NOTPASS));
		}
		resultBean.setData(findUser);
		log.info("==================用户：" + user.getName() + "登陆成功");
		HttpSession session = httpServletRequest.getSession(true);
		session.setAttribute("userId", findUser.getName());
		session.setMaxInactiveInterval(10 * 60);// 设置单位为秒，设置为-1永不过期
		return resultBean;
	}
	
	@ApiIgnore
	@ResponseBody
	@RequestMapping(value = "/user",method =RequestMethod.PUT, produces = { "application/json;charset=UTF-8" })
	public ResultBean<User> update(@Valid ReqUserRegisterVo requser, BindingResult result) {
		// 参数校验
		@SuppressWarnings("unchecked")
		ResultBean<User> validresult = ValidUtil.validByBindingResult(result);
		if (validresult != null) {
			return validresult;
		}
		User user = new User();
		BeanUtils.copyProperties(requser, user);
		// 返回结果
		ResultBean<User> resultBean = new ResultBean<User>();
		log.info("==================用户：" + user.getName() + "开始更新");
		boolean updateFlag = false;
		try {
			updateFlag = userService.updateByName(user);
		} catch (Exception e) {
			e.printStackTrace();
			return new ResultBean<User>(new BizException(ErrorEnum.OPRATE_EEROR));
		}
		if (!updateFlag) {
			log.info("==================用户：" + user.getName() + "更新失败");
			return new ResultBean<User>(new BizException(ErrorEnum.UPDATE_FAIL, "用户"));
		}
		log.info("==================用户：" + user.getName() + "注册成功");
		return resultBean;
	}
	@ApiIgnore
	@ResponseBody
	@RequestMapping(value = "/logout", produces = { "application/json;charset=UTF-8" })
	public Map logout(HttpServletRequest httpServletRequest) {
		HttpSession session = httpServletRequest.getSession(true);
		Object userId = session.getAttribute("userId");
		log.info("==================用户：" + userId + "开始注销");
		session.removeAttribute("userId");
		log.info("==================用户：" + userId + "注销成功");
		Map map = new HashMap();
		map.put("url", "登陆页面");
		return map;
	}
	
	@ApiIgnore
	@ResponseBody
	@RequestMapping(value = "/getUser",method =RequestMethod.GET, produces = { "application/json;charset=UTF-8" })
	public ResultBean<User> findUserInfo(ReqUserGetVo requser) {
		User userCondition =new User();
		BeanUtils.copyProperties(requser, userCondition);
		User user = userService.selectByName(userCondition);
		return new ResultBean<User>(user);
	}

}